﻿using Ecommerce.Areas.Manager.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ecommerce.Common;
using System.Web.Security;

namespace Ecommerce.Areas.Home.Controllers
{
    public class CheckoutController : Controller
    {

        private DatabaseContext db = new DatabaseContext();

        //
        // GET: /Home/Checkout/
        [EAuthorization(LoginPage = EConst.CUSTOMER_LOGIN_PATH)]
        public ActionResult Index()
        {
            Order o = new Order();
            o.CustomerID = Int32.Parse(this.User.Identity.Name);

            List<Product> lstP = Session[EConst.LIST_CART_NAME] == null ? new List<Product>() : (List<Product>)Session[EConst.LIST_CART_NAME];
            if (lstP == null || lstP.Count() == 0)
            {
                return RedirectToAction("Index", "Template");
            }

            string productID = string.Empty;
            List<int> lstProdID = new List<int>();

            foreach (Product p in lstP)
            {
                productID += p.ProductID + ",";
                lstProdID.Add(p.ProductID);
            }

            o.ProductID = productID;

            decimal totalPrice = db.Products.Where(x => lstProdID.Contains(x.ProductID)).Sum(x => x.Price);

            o.totalPrice = totalPrice;
            o.OrderDate = DateTime.Now;
            o.OrderStatus = (int)Ecommerce.Common.EcommerceEnum.OrderStatus.NotPay;

            db.Orders.Add(o);
            db.SaveChanges();

            Session[EConst.LIST_CART_NAME] = null;

            return null;
        }
    }
}
